#!/usr/bin/env python3
# coding: utf-8
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# This file is a part of the CANN Open Software.
# Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# ======================================================================================================================
import random
import torch
import numpy as np
import math
from typing import Union, List

from atk.case_generator.generator.generate_types import GENERATOR_REGISTRY
from atk.case_generator.generator.base_generator import CaseGenerator
from atk.configs.case_config import InputCaseConfig, CaseConfig

def get_random_factor_divisible_by_32(K):
    if K <= 0:
        raise ValueError("K 必须是正整数")
    
    # 找出所有正整数因子
    factors = set()
    for i in range(1, int(math.sqrt(K)) + 1):
        if K % i == 0:
            factors.add(i)
            factors.add(K // i)
    
    # 约束6：每个切分后的K必须为64的倍数
    divisible_by_32 = [f for f in factors if f % 32 == 0]
    
    if not divisible_by_32:
        raise ValueError(f"{K}没有能被32整除的因子")
    
    # 随机选择一个能被8整除的因子
    return random.choice(divisible_by_32)

@GENERATOR_REGISTRY.register("ascend_generate_grouped_matmul_swiglu_quant_a8w4")
class AscendGroupedMatmulSwigluQuant(CaseGenerator):
    def __init__(self, config):
        super().__init__(config)

    def after_input_config(
            self,
            index: int,
            input_case: Union[InputCaseConfig, List[InputCaseConfig]]
    ) -> Union[InputCaseConfig, List[InputCaseConfig]]:

        return input_case

    def after_case_config(self, case_config: CaseConfig) -> CaseConfig:
        x = case_config.inputs[0]
        weight = case_config.inputs[1]
        bias = case_config.inputs[2]
        weightScale = case_config.inputs[4]
        xScale = case_config.inputs[5]
        groupList = case_config.inputs[6]
        weightFormat = case_config.inputs[9]
        quantMode = case_config.inputs[10]
        E, M, K, N  = weight.shape[0], x.shape[0], x.shape[1], weightScale.shape[-1]
        # 约束1 : K < 65536; N < 10240;
        K = K if K < 65536 else 65536-64
        N = N if N <= 10240 else 10240
        # 约束2 : weight NZ场景， K 需要64对齐，N需要64对齐;
        K = (K if K % 64 == 0 else ((K + 63) // 64 * 64))
        N = (N if N % 64 == 0 else ((N + 63) // 64 * 64))
        
        x.shape = [M, K]
        weight.shape = [E, K, N]
        bias.shape = [E, N]
        if quantMode.range_values == 0: # pergroup 量化
            quantGroupSize = get_random_factor_divisible_by_32(K)
            weightScale.shape = [E, K // quantGroupSize, N]
        elif quantMode.range_values == 1: # perchannel 量化
            weightScale.shape = [E, N]
        xScale.shape = [M,]
        groupList.shape = [E,]
        return case_config